package cn.lanqiao.web.interceptors;

import cn.lanqiao.common.entity.Admin;
import cn.lanqiao.common.utile.Result;
import cn.lanqiao.web.utils.JwtUtils;
import cn.lanqiao.web.utils.RedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AdminLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil ;

    @Value("${redis.keys.login-tokens}")
    private String login_token ;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setContentType("text/html;charset=utf8");
        if(JwtUtils.checkToken(request)){//验证token合法行
            //查询redis,检查过期时间
            //1 通过request，获取user对象
            Admin admin = JwtUtils.getAdminByJwtToken(request) ;
            if(admin == null){
                return  false ;
            }

            //2 根据key,查询redis 中的token
            String key = login_token + admin.getUsername() ;
            String token = String.valueOf(redisUtil.get(key)) ;
            if(key == null){//token 过期
                Result result = Result.ok("token 过期,请重新登录",4002) ;
                ObjectMapper objectMapper = new ObjectMapper() ;
                String json = objectMapper.writeValueAsString(result) ;
                response.getWriter().print(json);
                return  false ;
            }

            //3 判断剩余有效时间
            long exTime = redisUtil.getExpire(key) ;
            System.out.println("exTIme :  " + exTime);
            // 4 如果快过期了，那么重新设置有效时间
            if(exTime < 10){
                redisUtil.set(key,token,60) ;
            }

            return true ;
        }

        Result result = Result.ok("非法 token,请重新登录",4003) ;
        ObjectMapper objectMapper = new ObjectMapper() ;
        String json = objectMapper.writeValueAsString(result) ;
        response.getWriter().print(json);
        return false;
    }
}
